import Layout from '@components/layout';
import { Add as AddApi } from '@lib/api/work';
import { ICategory } from '@lib/types';
import { getVideoId } from '@lib/utils';
import { Button, Card, Form, Input, message, Select, Spin } from 'antd';
import Router from 'next/router';
import * as React from 'react';
import { connect } from 'react-redux';
import Editor from '@components/editor';
import './edit.less';
import TagInput from '@components/TagInput';

interface IAddProps {
	category: ICategory[];
}

interface IAddState {
	work: {
		category_id: number;
		code: string;
		name: string;
		video: string;
		description: string;
		detail: string;
		tag: string[];
	};
	loading: boolean;
}

class Add extends React.Component<IAddProps, IAddState> {
	constructor(props: any) {
		super(props);
		this.state = {
			work: {
				category_id: 0,
				code: "",
				name: "",
				description: "",
				detail: "",
				video: "",
				tag: []
			},
			loading: false
		}
		this.onSubmit = this.onSubmit.bind(this);
		this.onInputChange = this.onInputChange.bind(this);
		this.onInputBlur = this.onInputBlur.bind(this);
	}
	public onInputChange(e: string | string[] | React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, name?: string) {
		const res: any = Object.assign({}, this.state.work);
		if (typeof (e) === "string" || (typeof (e) === "object" && e instanceof Array)) {
			if (typeof (name) === "string") res[name] = e;
		} else {
			res[e.target.name] = e.target.value;
		}
		this.setState({
			work: res
		});
	}
	public onInputBlur(e: React.FocusEvent<HTMLInputElement>) {
		const res = Object.assign({}, this.state.work);
		res.video = getVideoId(e.target.value) || "";
		this.setState({
			work: res
		});
	}
	public async onSubmit(e: React.FormEvent) {
		e.preventDefault();
		if (this.state.loading) {
			return;
		}
		this.setState({
			loading: true
		});
		const res = await AddApi(this.state.work);
		if (res instanceof Error) {
			message.error(res.message);
		} else {
			message.success('提交成功');
			Router.push("/my/work");
		}
		this.setState({
			loading: false
		});
	}
	public render() {
		const options = this.props.category.map(it => <Select.Option value={it.id} key={it.id}>{it.name}</Select.Option>);
		const codeValidate: any = (this.state.work.code === "" || /^(\w+)$/.test(this.state.work.code)) ? {} : {
			validateStatus: "error",
			help: "分享码无效。若有多个分享码请写在详情中"
		};
		const checkTag: any = (this.state.work.tag.join(',').length > 200 ? {
			validateStatus: "error",
			help: "标签太多了"
		} : {});
		return (
			<Layout title="提交作品" className="page-edit page-edit-add">
				<Card title="提交作品">
					<Spin spinning={this.state.loading}>
						<Form layout="horizontal" onSubmit={this.onSubmit}>
							<Form.Item label="作品名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								<Input name="name" onChange={this.onInputChange} required />
							</Form.Item>
							<Form.Item label="类别" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								<Select onChange={(id: string) => this.onInputChange(id, 'category_id')}>{options}</Select>
							</Form.Item>
							<Form.Item label="标签" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} {...checkTag}>
								<TagInput value={this.state.work.tag} onChange={(tags) => this.onInputChange(tags, 'tag')}></TagInput>
							</Form.Item>
							<Form.Item label="简介" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								<Input name="description" onChange={this.onInputChange} required />
							</Form.Item>
							<Form.Item label="视频" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} help="请直接粘贴视频地址，支持Bilibili、优酷、腾讯视频">
								<Input name="video" onChange={this.onInputChange} onBlur={this.onInputBlur} value={this.state.work.video} />
							</Form.Item>
							<Form.Item label="详情（Markdown）" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								<Editor value={this.state.work.detail} onChange={(text: string) => this.onInputChange(text, 'detail')} />
							</Form.Item>
							<Form.Item label="分享码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} {...codeValidate}>
								<Input name="code" onChange={this.onInputChange} required />
							</Form.Item>
							<Form.Item label="&nbsp;" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								<Button type="primary" htmlType="submit">提交</Button>
								<br />
								<small style={{ marginLeft: "8px" }}>提交完成后，您可以在“查看”页面右侧复制短地址，方便您在其他地方（如自定义说明、社交媒体上）使用</small>
							</Form.Item>
						</Form>
					</Spin>
				</Card>
			</Layout>
		);
	}
}

const mapStateToProps = (state: any) => ({
	category: state.category
});

export default connect(mapStateToProps)(Add);